/* eslint-disable react/no-danger */
import React, { useRef, FC, useState, useEffect } from 'react'

// import { useHistory } from 'react-router-dom'
import {
  Button,
  Select,
  Modal,
  Space,
  Tag,
  DatePicker,
  message,
  Input
} from 'antd'
import moment from 'moment'
import { useLocation } from 'react-router-dom'
import MyTable from '@/components/common/table'
import commom from '@/api'
import $axios from '@/utils/axios'
import formAxios from '@/utils/loginAxios'

const { RangePicker } = DatePicker

const today = moment().format('YYYY-MM-DD')

const dateFormat = 'YYYY-MM-DD HH:mm:ss'

interface Response {
  content?: any
}

interface TaskState {
  taskId?: any
  group?: any
}

const JobLogList: FC = () => {
  const tableRef: RefType = useRef()

  // const history = useHistory()

  // const [jobGroup, setJobGroup] = useState('0')
  // const [jobId, setJobId] = useState('0')

  // const param = history.location.state as TaskState
  // if (param != null) {
  //   setJobGroup(param.group)
  //   setJobId(param.taskId)
  // }

  const [jobGroupList, setJobGroupList] = useState([])
  const [jobGroupDefaultValue] = useState('0')

  const [jobIdList, setJobIdList] = useState([
    {
      label: '全部',
      value: '0'
    }
  ])
  const [jobIdDefaultValue] = useState('0')

  useEffect(() => {
    getJobGroupList()
  }, [])

  const location = useLocation()
  useEffect(() => {
    const jobGroup = (location.state as any)?.group ?? ''
    const taskId = (location.state as any)?.taskId ?? ''
    selectJobGroup(jobGroup)
    // 设置jobId
    tableRef.current?.setFieldsValue({
      jobId: taskId
    })
  }, [location.state])

  const getJobGroupList = async () => {
    const res = await $axios.get('/api/jobgroup/pageList?start=0&length=10000')
    const arr = []
    arr.push({
      label: '全部',
      value: '0'
    })
    if (res?.data?.length > 0) {
      const jobGroupData = res.data

      for (let i = 0; i < jobGroupData.length; i += 1) {
        arr.push({
          label: jobGroupData[i].title,
          value: `${jobGroupData[i].id}`
        })
      }
    }
    setJobGroupList(arr)
  }

  // 新开页面查看日志
  const viewLog = async (executorAddress, triggerTime, logId) => {
    setJobDetail('')
    const params = new URLSearchParams()
    params.append('executorAddress', executorAddress)
    params.append('triggerTime', triggerTime)
    params.append('logId', logId)
    params.append('fromLineNum', '1')
    const res = await formAxios.post('/api/joblog/logDetailCat', params)
    if (res.data.code === 200) {
      message.success('查询成功')
      setOpen(true)
      setJobDetail(res.data.content.logContent)
    } else {
      message.error('查询执行日志详情出错！')
    }
  }

  const [toStopLogId, setToStopLogId] = useState('')
  // 终止任务
  const stop = (id) => {
    Modal.confirm({
      title: '提示',
      content: '确认终止该任务？',
      onOk() {
        setToStopLogId(`${id}`)
        stopOneTask()
      },
      onCancel() {
        setToStopLogId('')
      }
    })
  }

  // 终止服务实际的处理逻辑
  const stopOneTask = async () => {
    const params = new URLSearchParams()
    params.append('id', toStopLogId)
    const res = await formAxios.post('/api/joblog/logKill', params)
    if (res.data.code === 200) {
      message.success('操作成功！')
    } else {
      message.error(res.data.msg || '操作失败！')
    }
  }

  const DeleteLogBtn = () => (
    <Button
      className="fr"
      onClick={() => message.error('功能暂不支持！')}
      type="primary"
    >
      清理
    </Button>
  )

  const viewRemark = (remark) => {
    Modal.info({
      title: '查看',
      // eslint-disable-next-line react/no-danger
      content: <div dangerouslySetInnerHTML={{ __html: remark }} />,
      onOk() {}
    })
  }

  const timestampToTime = (timestamp) => {
    if (Number.isNaN(timestamp)) {
      return ''
    }
    const date = new Date(timestamp)
    const Y = `${date.getFullYear()}-`
    const M = `${
      date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
    }-`
    const D = `${date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()} `
    const h = `${
      date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()
    }:`
    const m = `${
      date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes()
    }:`
    const s =
      date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds()
    return Y + M + D + h + m + s
  }

  const beforeSearch = (values) => {
    if (values != null && values.filterTime != null) {
      const { filterTime } = values
      if (filterTime != null && filterTime.length === 2) {
        values.filterTime = `${filterTime[0].format(
          dateFormat
        )} - ${filterTime[1].format(dateFormat)}`
      }
    }
  }

  const selectJobGroup = async (val) => {
    const arr = []
    arr.push({
      label: '全部',
      value: '0'
    })
    if (val) {
      const json: object = { jobGroup: val }
      const res = await $axios.get('/api/joblog/getJobsByGroup', json)
      const data = res as Response
      if (data.content != null && data.content.length > 0) {
        const jobTaskData = data.content

        for (let i = 0; i < jobTaskData.length; i += 1) {
          arr.push({
            label: jobTaskData[i].jobDesc,
            value: `${jobTaskData[i].id}`
          })
        }
      }
    }
    setJobIdList(arr)
  }

  // 搜索栏配置项
  const searchConfigList = [
    {
      name: '执行器',
      key: 'jobGroup',
      width: 200,
      textWrap: 'word-break',
      ellipsis: true,
      slot: (
        <Select
          options={jobGroupList}
          placeholder="请选择执行器"
          style={{ width: 250 }}
          defaultValue={jobGroupList.length === 0 ? '0' : jobGroupList[0].value}
          onSelect={selectJobGroup}
          onChange={selectJobGroup}
          // value={jobGroup}
        />
      ),
      initialValue: jobGroupDefaultValue
    },
    {
      name: '任务',
      key: 'jobId',
      width: 200,
      textWrap: 'word-break',
      ellipsis: true,
      slot: (
        <Select
          options={jobIdList}
          placeholder="请选择任务"
          style={{ width: 250 }}
          defaultValue={jobIdList.length === 0 ? '0' : jobIdList[0].value}
          // value={jobId}
        />
      ),
      initialValue: jobIdDefaultValue
    },
    {
      name: '状态',
      key: 'logStatus',
      width: 50,
      textWrap: 'word-break',
      ellipsis: true,
      slot: (
        <Select
          options={[
            { label: '全部', value: '-1' },
            { label: '成功', value: '1' },
            { label: '失败', value: '2' },
            { label: '进行中', value: '3' }
          ]}
          defaultValue="-1"
        />
      ),
      initialValue: '-1'
    },
    {
      name: '调度时间',
      key: 'filterTime',
      width: 50,
      textWrap: 'word-break',
      ellipsis: true,
      slot: (
        <RangePicker
          showTime
          format={dateFormat}
          defaultValue={[
            moment(`${today} 00:00:00`, dateFormat),
            moment(`${today} 23:59:59`, dateFormat)
          ]}
        />
      ),
      initialValue: [
        moment(`${today} 00:00:00`, dateFormat),
        moment(`${today} 23:59:59`, dateFormat)
      ]
    }
  ]
  const columns = [
    {
      title: '任务ID',
      dataIndex: 'jobId',
      render: (text, record) => {
        let jobhandler = ''
        if (record.executorHandler) {
          jobhandler = `<br>JobHandler：${record.executorHandler}`
        }
        let temp = ''
        temp += `执行器：${
          record.executorAddress ? record.executorAddress : ''
        }`
        temp += jobhandler
        temp += `<br>任务参数：${record.executorParam}`
        return (
          <Space size="middle">
            <button
              type="button"
              onClick={() => viewRemark(temp)}
              style={{ color: 'blue' }}
            >
              {text}
            </button>
          </Space>
        )
      }
    },
    {
      title: '调度时间',
      dataIndex: 'triggerTime',
      render: (text) => {
        return timestampToTime(Date.parse(text))
      }
    },
    {
      title: '调度结果',
      dataIndex: 'triggerCode',
      render: (text) => {
        if (text === 200) {
          return <Tag color="green">成功</Tag>
        }
        if (text === 500) {
          return <Tag color="red">失败</Tag>
        }
        return text
      }
    },
    {
      title: '调度备注',
      dataIndex: 'triggerMsg',
      render: (text, record) => {
        return (
          <Space size="middle">
            <button
              type="button"
              onClick={() => viewRemark(record.triggerMsg)}
              style={{ color: 'blue' }}
            >
              查看
            </button>
          </Space>
        )
      }
    },
    {
      title: '执行时间',
      dataIndex: 'handleTime',
      render: (text) => {
        return timestampToTime(Date.parse(text))
      }
    },
    {
      title: '执行结果',
      dataIndex: 'handleCode',
      render: (text) => {
        if (text === 200) {
          return <Tag color="green">成功</Tag>
        }
        if (text === 500) {
          return <Tag color="red">失败</Tag>
        }
        return ''
      }
    },
    {
      title: '执行备注',
      dataIndex: 'handleMsg',
      render: (text, record) => {
        if (!record.handleMsg) {
          return '无'
        }
        return (
          <Space size="middle">
            <button
              type="button"
              onClick={() => viewRemark(record.handleMsg)}
              style={{ color: 'blue' }}
            >
              查看
            </button>
          </Space>
        )
      }
    },
    {
      title: '操作',
      dataIndex: 'operations',
      align: 'center',
      render: (text, record) => {
        if (record.triggerCode === 200 || record.handleCode !== 0) {
          return (
            <>
              <Button
                className="btn"
                onClick={
                  () =>
                    viewLog(
                      record.executorAddress,
                      Date.parse(record.triggerTime),
                      record.id
                    )
                  // eslint-disable-next-line react/jsx-curly-newline
                }
              >
                执行日志
              </Button>
              {record.handleCode === 0 && (
                <Button className="btn" onClick={() => stop(record.id)}>
                  终止任务
                </Button>
              )}
            </>
          )
        }
        return ''
      }
    }
  ]

  const [open, setOpen] = useState(false)
  const [jobDetail, setJobDetail] = useState('')
  const { TextArea } = Input
  return (
    <>
      <DeleteLogBtn />
      <MyTable
        apiFun={commom.getJobLogList}
        columns={columns}
        ref={tableRef}
        searchConfigList={searchConfigList}
        beforeSearch={beforeSearch}
      />
      <Modal
        title="查询执行日志详情"
        centered
        visible={open}
        onOk={() => setOpen(false)}
        onCancel={() => setOpen(false)}
        width={1000}
      >
        <TextArea autoSize value={jobDetail.replaceAll('<br>', '\n')} />
      </Modal>
    </>
  )
}
export default JobLogList
